package controller

import (
	"goWeb/bookStore/dao"
	"goWeb/bookStore/model"
	"goWeb/bookStore/utils"
	"html/template"
	"net/http"
)

func Login(w http.ResponseWriter, r *http.Request) {
	t := template.Must(template.ParseFiles("views/pages/user/login.html"))
	t.Execute(w, "")
}

func CheckLogin(w http.ResponseWriter, r *http.Request) {
	flag, _ := dao.IsLogin(r)
	if flag {
		//已经登录过了
		GetBookByPrice(w, r)
	} else {
		username := r.PostFormValue("username")
		password := r.PostFormValue("password")
		user, _ := dao.ValidateUser(username, password)
		if user.Id > 0 {
			//创建一个session
			sess := &model.Session{
				SessionId: utils.CreateUUID(),
				Username:  username,
				Userid:    user.Id,
			}
			//添加session到数据库
			dao.AddSession(sess)
			//创建一个cookie
			var cookie = &http.Cookie{
				Name:     "user",
				Value:    sess.SessionId,
				HttpOnly: true,
			}
			//设置cookie的value为session的sessionid
			http.SetCookie(w, cookie)
			t := template.Must(template.ParseFiles("views/pages/user/login_success.html"))
			t.Execute(w, user)
		} else {
			t := template.Must(template.ParseFiles("views/pages/user/login.html"))
			t.Execute(w, "您输入的用户名或者密码不正确")
		}
	}

}

func LogOut(w http.ResponseWriter, r *http.Request) {
	cookie, _ := r.Cookie("user")
	if cookie != nil {
		dao.DelSession(cookie.Value)
		cookie.MaxAge = -1
		http.SetCookie(w, cookie)
	}
	GetBookByPrice(w, r)
}

func Register(w http.ResponseWriter, r *http.Request) {
	t := template.Must(template.ParseFiles("views/pages/user/regist.html"))
	t.Execute(w, "")
}

func CheckRegister(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")
	email := r.PostFormValue("email")
	user, _ := dao.GetUserByName(username)
	if user.Id > 0 {
		t := template.Must(template.ParseFiles("views/pages/user/regist.html"))
		t.Execute(w, "用户已注册")
	} else {
		dao.RegisterUser(username, password, email)
		t := template.Must(template.ParseFiles("views/pages/user/regist_success.html"))
		t.Execute(w, "")
	}
}

//CheckUserName
func CheckUserName(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	user, _ := dao.GetUserByName(username)
	if user.Id > 0 {
		//用户名已存在
		w.Write([]byte("true"))
	} else {
		w.Write([]byte("false"))
	}

}
